#include <iostream>

using std::cout;
using std::endl;

//单例模式的设计需求：一个类只能有一个对象
//思路：
//1、创建的对象肯定是要入内存的，也就是用户态的那块空间
//2、不能在类外面创建对象，所以就在类中进行创建
//3、为了让类外的对象创建报错，将构造函数设置为私有的
//
//使用场景：全局唯一的对象，网页库、日志记录器

class Singleton
{
public:
    static Singleton *getInstance()
    {
        if(nullptr == _pInstance)
        {
            _pInstance = new Singleton();//在类中创建堆对象
        }

        return _pInstance;
    }

    static void destroy()
    {
        if(_pInstance)
        {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

private:
    Singleton()
    {
        cout << "Singleton()" << endl;
    }

    ~Singleton()
    {
        cout << "~Singleton()" << endl;
    }
private:
    static Singleton *_pInstance;
};

//静态数据成员的初始化
Singleton *Singleton::_pInstance = nullptr;

/* Singleton gS1;//全局区,error */
/* Singleton gS2;//全局区 */

int main(int argc, char **argv)
{
    /* Singleton s1;//栈区,error */
    /* Singleton s2;//栈区 */

    /* Singleton *ps1 = new Singleton();//堆区,error */
    /* Singleton *ps2 = new Singleton(); */

    /* printf("&s1 = %p\n", &s1); */
    /* printf("&s2 = %p\n", &s2); */
    /* printf("ps1 = %p\n", ps1); */
    /* printf("ps2 = %p\n", ps2); */

    Singleton *ps1 = Singleton::getInstance();
    Singleton *ps2 = Singleton::getInstance();
    cout << "ps1 = " << ps1 << endl;
    cout << "ps2 = " << ps2 << endl;

    /* Singleton::getInstance()->destroy(); */

    Singleton::destroy();
    Singleton::destroy();
    Singleton::destroy();

    /* delete ps1;//error */
    /* delete ps2;//error */

    return 0;
}

